package edu.ustb.efws.pipeline.collect.handler;

import edu.ustb.efws.EfwsProperties;
import edu.ustb.efws.pipeline.collect.Collect;
import edu.ustb.efws.pipeline.collect.cache.MaxICacheService;
import edu.ustb.efws.pipeline.domain.Kyj;
import edu.ustb.efws.pipeline.domain.KyjLog;
import edu.ustb.efws.pipeline.service.KyjLogService;
import edu.ustb.efws.utils.DateUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 空压机设备数据处理
 *
 * @author TS Group
 */
class KyjLogHandler implements PipelineHandler {
    private final KyjLogService service;
    private final MaxICacheService maxICacheService;
    private final EfwsProperties properties;

    KyjLogHandler(KyjLogService service, MaxICacheService maxICacheService, EfwsProperties properties) {
        this.service = service;
        this.maxICacheService = maxICacheService;
        this.properties = properties;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Optional<Object> handle0(Object data) {
        Collect collect = (Collect)data;
        List<Kyj> kYJs = (List<Kyj>)collect.getData();
        if(kYJs == null || kYJs.isEmpty()){
            return Optional.empty();
        }

        kYJs = filterWorkTime(kYJs);
        if(kYJs.isEmpty()){
            return Optional.empty();
        }

        List<KyjLog> logs = kYJs.stream().map(this::newKyjLog).collect(Collectors.toList());
        service.save(collect.getColTableName(), logs);
        return Optional.of(logs);
    }

    private List<Kyj> filterWorkTime(List<Kyj> logs){
        return logs.stream().filter(e -> {
            LocalDateTime localDateTime = DateUtils.dateToLocalDataTime(e.getTime());
            int minute = localDateTime.getHour() * 60 + localDateTime.getMinute();
            return minute >= properties.getMeterStartMinute() && minute <= properties.getMeterEndMinute();
        }).collect(Collectors.toList());
    }

    private KyjLog newKyjLog(Kyj t){
        KyjLog log = new KyjLog();

        log.setDetectorId(t.getDetectorId());
        log.setMonth(DateUtils.dateToMonthNum(t.getTime()));
        log.setI1(t.getI1());
        log.setI2(t.getI2());
        log.setI3(t.getI3());
        log.setMaxI(Math.max(t.getI1(), Math.max(t.getI2(), t.getI3())));
        log.setCollectTime(t.getTime());

        updateMaxI(log);

        return log;
    }

    private void updateMaxI(KyjLog t){
        maxICacheService.put(t.getDetectorId(), t.getMaxI());
    }
}
